package cn.acrdpm.producer;

import cn.acrdpm.constant.ResponseCode;
import cn.acrdpm.constant.ServerResponse;
import cn.acrdpm.entity.Mail;
import cn.acrdpm.entity.MsgLogWithBLOBs;
import cn.acrdpm.entity.MyMessage;
import cn.acrdpm.mapper.MsgLogMapper;
import cn.acrdpm.tools.CheckIpUtils;
import cn.acrdpm.tools.IpTool;
import cn.acrdpm.tools.JsonUtils;
import cn.acrdpm.tools.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 *  消息生产者
 * @author 张敏
 * @date 2021/3/11
 */
@Slf4j
@PropertySource("classpath:rabbitmq.properties")
@Component
public class MqProducer {

    @Value("${com.acrdpm.directexchange}")
    private String directExchange;

    @Value("${com.acrdpm.topicexchange}")
    private String topicExchange;

    @Value("${com.acrdpm.fanoutexchange}")
    private String fanoutExchange;

    @Value("${com.acrdpm.directroutingkey}")
    private String directRoutingKey;

    @Value("${com.acrdpm.topicroutingkey1}")
    private String topicRoutingKey1;

    @Value("${com.acrdpm.topicroutingkey2}")
    private String topicRoutingKey2;

    /**
     * 发送邮件
     */
    @Value("${mail_topic_queue}")
    private String mailTopicQueue;

    @Value("${mail_topic_exchange}")
    private String mailTopicExchange;

    @Value("${mail_topic_routingKey}")
    private String mailTopicRoutingKey;


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IpTool ipTool;

    @Resource
    private MsgLogMapper msgLogMapper;

    public void createMessage(MyMessage myMessage) {

        rabbitTemplate.convertAndSend(topicExchange, topicRoutingKey1,
                CheckIpUtils.makeMessage(myMessage, ipTool.getIp()));
    }

    public ServerResponse sendMail(Mail mail) {
        String msgId = RandomUtil.UUID32();
        //设置邮件id
        mail.setMsgId(msgId);

        MsgLogWithBLOBs msgLog = new MsgLogWithBLOBs();
        msgLog.setMsgId(msgId);
        msgLog.setMsg(JsonUtils.toJson(mail));
        msgLog.setExchange(mailTopicExchange);
        msgLog.setRoutingKey(mailTopicRoutingKey);
        // 消息入库
        log.info("消息信息:msglog {}" ,msgLog);
        msgLogMapper.insertSelective(msgLog);
        //生成消息的唯一id
        CorrelationData correlationData = new CorrelationData(msgId);
        // 发送消息
        rabbitTemplate.convertAndSend(mailTopicExchange, mailTopicRoutingKey, mail, correlationData);

        return ServerResponse.success(ResponseCode.MAIL_SEND_SUCCESS.getMsg());
    }
}
